<?php
require(APPPATH.'libraries/REST_Controller.php');

class Request extends REST_Controller {

	public function item_post()
	{
		$item_barcode = $this->post('item_barcode');
		$branch_id = $this->post('branch_id');
		$request_amount = $this->post('request_amount');
		$error = array();
		if ($item_barcode == null){
			array_push($error, 'item_barcode is required');
		}
		if(!is_int(intval($item_barcode))){
			array_push($error,'invalid item_barcode');
		}
		if ($branch_id == null){
			array_push($error, 'branch_id is required');
		}
		if(!is_int(intval($branch_id))){
			array_push($error,'invalid branch_id');
		}
		if ($request_amount == null){
			array_push($error, 'request_amount is required');
		}
		if(!is_numeric($request_amount) || $request_amount < 0){
			array_push($error,'invalid request_amount');
		}
		if (sizeof($error)>0){
			$this->response($error, 400);
		}
		$this->load->model('request_model');
		$request_id = $this->request_model->add($item_barcode, $branch_id, $request_amount);
		if ($request_id > 0){
			$this->response($request_id, 201);
		}else
			$this->response(null,404);
	}

	protected function item_received_post()
	{
		$request_id = $this->post('request_id');
		$branch_id = $this->post('branch_id');
		$error = array();
		if ($branch_id == null){
			array_push($error, 'branch_id is required');
		}
		if(!is_int(intval($branch_id))){
			array_push($error,'invalid branch_id');
		}
		if ($request_id == null){
			array_push($error, 'request_id is required');
		}
		if(!is_int(intval($request_id))){
			array_push($error,'invalid request_id');
		}
		if (sizeof($error) > 0){
			$this->response($error, 400);
		}
		$this->load->model('request_model');
		if ($this->request_model->received($request_id, $branch_id)){
			$this->response('updated', 202);
		}else
			$this->response('fail to update',404);
	}
}